//
//  SYPhotoBrowserModalAnimated.swift
//  SingWeibo
//
//  Created by shiying on 16/1/2.
//  Copyright © 2016年 shiying. All rights reserved.
//

import UIKit

class SYPhotoBrowserModalAnimated: NSObject, UIViewControllerAnimatedTransitioning {

    // 动画时间
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.25
    }
    
    // 实现modal动画
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! SYPhotoBrowserViewController
        
        // 获取到modal出来的控制器View
        let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
        // 添加到父容器
        transitionContext.containerView()?.addSubview(toView)
        
        let tempImageView = toVC.modalTempImageView()
        // 将过渡视图添加到容器视图里面
        transitionContext.containerView()?.addSubview(tempImageView)
        // 透明度
        toView.alpha = 0
        // 需要先隐藏collectionView
        toVC.collectionView.hidden = true
        
        
        UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
            toView.alpha = 1 // 恢复透明度
            
            // 让过渡视图缩放到目标位置
            tempImageView.frame = toVC.modalTargetRect()
            }) { (_) -> Void in
                tempImageView.removeFromSuperview() // 移除过渡视图
                toVC.collectionView.hidden = false // 显示
                
                // 完成回调
                transitionContext.completeTransition(true)
        }
    }
}